#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

struct Node* copyRandomList(struct Node* head) {
    struct Node* cur = head;
    while (cur) {
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode->val = cur->val;
        newNode->next = cur->next;
        cur->next = newNode;
        cur = cur->next->next;
    }
    cur = head;
    while (cur) {
        struct Node* newNode = cur->next;
        if (cur->random == NULL) {
            newNode->random = NULL;
        }
        else {
            newNode->random = cur->random->next;
        }
        cur = cur->next->next;
    }
    struct Node* newList = NULL, * tail = NULL;
    cur = head;
    while (cur) {
        struct Node* newNode = cur->next;
        struct Node* next = newNode->next;
        if (tail == NULL) {
            newList = tail = newNode;
        }
        else
        {
            tail->next = newNode;
            tail = tail->next;
        }
        cur->next = next;
        cur = next;
    }
    return newList;
}